import { defineStore } from "pinia";
import { useRouter } from "vue-router";
import { getCurUser, getCurUserMenu, findMenuListApi, getAllDic } from "../api/index";

const router = useRouter();
export const usePermissStore = defineStore("permiss", {
  state: () => {
    return {
      isShow: {},
      menu: [],
      userInfo: null,
      allDic: null
    };
  },
  actions: {
    //更改key数据
    // handleSet(val) {
    // 	this.key = val;
    // },
    async setDisabled() {
      try {
        //获取所有菜单列表
        await findMenuListApi().then(async (res) => {
          await this.getAllNodeId(res.data.data, 1);
        });
        this.menu = [];
        //获取当前登录用户数据
        await getCurUserMenu()
          .then((res) => {
            if (res.data.data) {
              // this.userInfo = res.data.data;
              this.menu = this.filterateData(
                JSON.parse(JSON.stringify(res.data.data)),
                1
              );
              this.getAllNodeId(res.data.data, 2);
              // console.log(this.menu)
            }
          })
          .catch((err) => {
            router.push("/login");
          });
      } catch (error) {
        return error;
      }
    },
    //递归取出所有权限id
    //data:数据对象
    //type:遍历类型1所有权限2当前用户拥有的权限
    getAllNodeId(data: any, type: number) {
      if (!data) return;
      for (let i = 0; i < data.length; i++) {
        if (type === 1) {
          this.isShow[data[i].id] = false;
          if (data[i].children.length != 0) {
            this.getAllNodeId(data[i].children, 1);
          }
        }
        if (type === 2) {
          this.isShow[data[i].id] = true;
          if (data[i].children.length > 0) {
            this.getAllNodeId(data[i].children, 2);
          }
        }
      }
    },
    //过滤菜单递归方法
    filterateData(data: any, type: number) {
      if (!data) return;
      let menu = data;
      menu.forEach((val, index, arr) => {
        if (val.type != type) {
          delete arr[index];
        }
        if (val.children.length > 0) {
          this.filterateData(val.children, type);
        }
        if (val.children[0] == undefined) {
          delete val.children;
        }
      });
      return menu;
    },
    //获取当前登录用户数据
    async getCurUserInfo() {
      await getCurUser().then((res) => {
        if (res.data.code === 2000) {
          this.userInfo = res.data.data;
        }
      });
      return true;
    },
    // 时间戳转换方法
    // timestamp: 时间戳
    timeConversion(timestamp) {
      let date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + "-";
      var M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      var D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
      var h =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      var m =
        (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
        ":";
      var s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return Y + M + D + h + m + s;
    },
    //获取所有数据字典
    async getDataDictionary() {
      await getAllDic().then((res) => {
        if (res.data.code === 2000) {
          this.allDic = res.data.data.dicMap;
          // console.log(this.allDic);
        }
      });
    },

    /**
    * @desc 函数防抖
    * @param func 目标函数
    * @param wait 延迟执行毫秒数
    * @param immediate true - 立即执行， false - 延迟执行
    */
    debounce(func, wait = 1000, immediate = true) {
      let timer;
      return function () {
        let context = this,
          args = arguments;
        if (timer) clearTimeout(timer);
        if (immediate) {
          let callNow = !timer;
          timer = setTimeout(() => {
            timer = null;
          }, wait);
          if (callNow) func.apply(context, args);
        } else {
          timer = setTimeout(() => {
            func.apply(context, args);
          }, wait)
        }
      }
    },
    /**
    * @desc 输入框动态宽度
    * @param val 输入框内容
    * @param defLength 默认长度
    * @param maxLength 超过maxLength增加宽度
    */
    handleLength(val, defLength, maxLength = 1) {
      if (val) {
        let strLength = (val + '').length;
        if (strLength > maxLength) {
          return (strLength - maxLength) * 8 + defLength + "px";
        } else {
          return defLength + 'px';
        }
      } else {
        return defLength + 'px';
      }
    }
  },
});
